package com.travel.interceptor;

import com.travel.mapper.log.ApiLogMapper;
import com.travel.model.entity.log.ApiLog;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
//api统计拦截器 统计api请求和响应时间
@Component
@RequiredArgsConstructor
public class ApiStatisticsInterceptor implements HandlerInterceptor {
    
    private final ApiLogMapper apiLogMapper;
    private final ThreadLocal<Long> startTime = new ThreadLocal<>();
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        startTime.set(System.currentTimeMillis());
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
            Object handler, Exception ex) {
        try {
            Long start = startTime.get();
            if (start != null) {
                long duration = System.currentTimeMillis() - start;
                
                ApiLog apiLog = ApiLog.builder()
                    .path(request.getRequestURI())
                    .method(request.getMethod())
                    .requestTime(LocalDateTime.now())
                    .responseTime(duration)
                    .statusCode(response.getStatus())
                    .clientIp(getClientIp(request))
                    .userAgent(request.getHeader("User-Agent"))
                    .build();
                    
                apiLogMapper.insert(apiLog);
            }
        } finally {
            startTime.remove();
        }
    }
    
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
} 